package org.pearl.springbootsecurity.demo.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.pearl.springbootsecurity.demo.entity.Permission;
import org.pearl.springbootsecurity.demo.entity.Role;
import org.pearl.springbootsecurity.demo.pojo.UserInfoDO;
import org.pearl.springbootsecurity.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by TD on 2021/7/6
 * 自定义加载用户信息接口实现
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * @param username 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 数据库查询用户
        /*User user = userService.getUserByName(username);*/
        UserInfoDO userInfoDO = userService.getUserInfoByName(username);
        if (userInfoDO == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 2. 设置权限集合，后续需要数据库查询
/*        List<GrantedAuthority> authorityList =
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");*/
        // 2. 角色权限集合转为  List<GrantedAuthority>
        List<Role> roleList = userInfoDO.getRoleList();
        List<Permission> permissionList = userInfoDO.getPermissionList();
        List<GrantedAuthority> authorityList=new ArrayList<>();
       /* roleList.forEach(e->{
            String roleCode = e.getRoleCode();
            if (StringUtils.isNotBlank(roleCode)){
                SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(roleCode);
                authorityList.add(simpleGrantedAuthority);
            }
        });
        permissionList.forEach(e->{
            String code = e.getCode();
            if (StringUtils.isNotBlank(code)){
                SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(code);
                authorityList.add(simpleGrantedAuthority);
            }
        });*/
        // 3. 返回自定义的用户信息
        MyUser myUser = new MyUser(userInfoDO.getUserName(), userInfoDO.getPassword(), authorityList);
        // 设置自定义扩展信息
        myUser.setDeptId(userInfoDO.getOrganizationId());
        myUser.setLoginTime(new Date());
        return myUser;
    }
}
